package com.sky.service.impl;

import com.sky.constant.MessageConstant;
import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.exception.OrderBusinessException;
import com.sky.mapper.OrderMapper;
import com.sky.service.GoodsSalesService;
import com.sky.vo.SalesTop10ReportVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class GoodsSalesServiceImpl implements GoodsSalesService {

    @Autowired
    private OrderMapper orderMapper;

    /**
     * 销量排名统计接口
     * @param begin 开始时间
     * @param end   结束时间
     * @return
     */
    @Override
    public SalesTop10ReportVO saleStatistics(LocalDate begin, LocalDate end) {
        // 起止时间
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);

        // 商品名称列表
        List<String> nameList = new ArrayList<>();
        // 销量列表
        List<Integer> numberList = new ArrayList<>();

        // 查询销量前10的菜品
        List<GoodsSalesDTO> dataList = orderMapper.getTop10(beginTime, endTime, Orders.COMPLETED);

        // 通过流的方式获取商品名称和销量列表
        // nameList = dataList.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        // numberList = dataList.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());

        if (dataList != null && !dataList.isEmpty()) {
            for (GoodsSalesDTO goodsSalesDTO : dataList) {
                String name = goodsSalesDTO.getName();
                Integer number = goodsSalesDTO.getNumber();
                nameList.add(name);
                numberList.add(number);
            }
        } else {
            throw new RuntimeException("列表为空,请确认数据!");
        }
        return SalesTop10ReportVO
                .builder()
                .nameList(StringUtils.join(nameList,","))
                .numberList(StringUtils.join(numberList,","))
                .build();
    }
}
